import { useCallback } from 'react';
import { REG_PROTOCOL } from 'esy-ui';
import { useNavigate as useAutoNavigate, NavigateOptions } from 'react-router-dom';
import { ssGetJsonItem } from '@/utils';
import { noSignAceRouter } from '@/constants';

export const useNavigation = () => {
  const autoNavigate = useAutoNavigate();
  const navigate = useCallback(
    (p, option?: NavigateOptions) => {
      if (REG_PROTOCOL.test(p)) {
        const w = window.open('about:_blank');
        if (w) w.location.href = p;
        return;
      }
      const userInfo = ssGetJsonItem('userInfo');
      // 未登录
      if (!userInfo?.Token && !noSignAceRouter.test(p) && p !== -1) {
        autoNavigate('/login', { replace: true });
      } else {
        autoNavigate(p, option);
      }
    },
    [autoNavigate],
  );

  return navigate;
};
